<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="决策树," />





  <link rel="alternate" href="/blog/atom.xml" title="稻草人的编程之路" type="application/atom+xml" />






<meta name="description" content="决策树这篇博客我们介绍决策树。决策树也是机器学习中非常厉害的一个算法 算法并没有好坏之分，只有哪个算法更适合哪个场景。只要是能解决问题的，且效果好的，就是一种很厉害的算法。决策树既可以做分类也可以做回归。 那么决策树是一个什么样的算法呢？   首先顾名思义，决策树是一个树模型，一个倒挂的树，类似linux的文件树一致 从根节点一步步走到叶子节点（这就是一个决策的过程） 所有的数据最终都会落到叶子节">
<meta name="keywords" content="决策树">
<meta property="og:type" content="article">
<meta property="og:title" content="机器学习之决策树算法">
<meta property="og:url" content="https://wangxiaochuang.github.io/2018/10/20/1.html">
<meta property="og:site_name" content="稻草人的编程之路">
<meta property="og:description" content="决策树这篇博客我们介绍决策树。决策树也是机器学习中非常厉害的一个算法 算法并没有好坏之分，只有哪个算法更适合哪个场景。只要是能解决问题的，且效果好的，就是一种很厉害的算法。决策树既可以做分类也可以做回归。 那么决策树是一个什么样的算法呢？   首先顾名思义，决策树是一个树模型，一个倒挂的树，类似linux的文件树一致 从根节点一步步走到叶子节点（这就是一个决策的过程） 所有的数据最终都会落到叶子节">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/10/20/1/func.png">
<meta property="og:updated_time" content="2019-01-07T22:36:29.352Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="机器学习之决策树算法">
<meta name="twitter:description" content="决策树这篇博客我们介绍决策树。决策树也是机器学习中非常厉害的一个算法 算法并没有好坏之分，只有哪个算法更适合哪个场景。只要是能解决问题的，且效果好的，就是一种很厉害的算法。决策树既可以做分类也可以做回归。 那么决策树是一个什么样的算法呢？   首先顾名思义，决策树是一个树模型，一个倒挂的树，类似linux的文件树一致 从根节点一步步走到叶子节点（这就是一个决策的过程） 所有的数据最终都会落到叶子节">
<meta name="twitter:image" content="https://wangxiaochuang.github.io/blog/2018/10/20/1/func.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://wangxiaochuang.github.io/2018/10/20/1.html"/>





  <title>机器学习之决策树算法 | 稻草人的编程之路</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">稻草人的编程之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">众人皆醉我独醒 举世皆浊我独清</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://wangxiaochuang.github.io/blog/2018/10/20/1.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="jackstraw">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="稻草人的编程之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">机器学习之决策树算法</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-20T01:43:45+00:00">
                2018-10-20
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/机器学习/" itemprop="url" rel="index">
                    <span itemprop="name">机器学习</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/机器学习/决策树/" itemprop="url" rel="index">
                    <span itemprop="name">决策树</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2018/10/20/1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/blog/2018/10/20/1.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/blog/2018/10/20/1.html" class="leancloud_visitors" data-flag-title="机器学习之决策树算法">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="决策树"><a href="#决策树" class="headerlink" title="决策树"></a>决策树</h1><p>这篇博客我们介绍决策树。决策树也是机器学习中非常厉害的一个算法</p>
<p>算法并没有好坏之分，只有哪个算法更适合哪个场景。只要是能解决问题的，且效果好的，就是一种很厉害的算法。决策树既可以做分类也可以做回归。</p>
<p>那么决策树是一个什么样的算法呢？</p>
<blockquote>
<ol>
<li>首先顾名思义，决策树是一个树模型，一个倒挂的树，类似linux的文件树一致</li>
<li>从根节点一步步走到叶子节点（这就是一个决策的过程）</li>
<li>所有的数据最终都会落到叶子节点，既可以做分类也可以做回归</li>
<li>由根节点（第一个选择点）、非叶子节点与分支（中间过程）、叶子节点（最终决策结果）</li>
</ol>
</blockquote>
<p>这些节点都表达了什么含义呢？</p>
<blockquote>
<ol>
<li>节点越多表示数据划分得越细</li>
<li>所有的叶子节点都表示是一个决策后的结果</li>
<li>理论上有几个特征，我们就有几个分支</li>
</ol>
</blockquote>
<h2 id="决策树训练与测试"><a href="#决策树训练与测试" class="headerlink" title="决策树训练与测试"></a>决策树训练与测试</h2><p>训练阶段：从给定的训练集构造一棵树（从根节点开始选择特征，需要考虑怎么选择好的特征）</p>
<p>测试阶段：这个阶段非常容易，将测试数据放到决策树中，从上到下走一遍就好了</p>
<p>主要的工作：找到具有决定性作用的特征，根据决定性作用的程度去构造倒挂树，决定性作用最大的作为根节点，后续类推。怎么判断决定性作用的程度呢，根据熵值。</p>
<h3 id="衡量标准-熵"><a href="#衡量标准-熵" class="headerlink" title="衡量标准-熵"></a>衡量标准-熵</h3><p>熵是物理或者化学中常用的一个词，表示随机变量不确定性的一种度量（表示了物体内部的混乱程度）</p>
<p>通俗解释一下：比如到一个杂货市场去买东西，买大一只铅笔的可能性是很低的，因为东西种类太多，每个种类取到的概率都很小，就说这个熵值很高。去苹果专卖店去买苹果设备的熵值就很低，因为买到的一定是苹果设备</p>
<p>公式：$H(X) = - \sum_{i=1}^n p_i * log{p_i} \text{（i表示：第i个类别）}$ </p>
<img src="/blog/2018/10/20/1/func.png" title="在下采样测试样本下混淆矩阵">
<p>假设现在有两个集合A和B：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">A = &#123;1,1,1,1,1,1,1,1,2,2&#125;</span><br><span class="line">B = &#123;1,2,3,4,5,6,7,8,9,1&#125;</span><br></pre></td></tr></table></figure>
<p>A集合就两个类别，整体的熵值是小于B集合的。那么想象一下，我们的决策树模型的构造过程中，按某个特征划分得时候我们是更想要得到哪种集合的数据呢？必然是A集合吧（为什么？说明分类很有效果啊，如果什么类型的数据都有，还有必要分这个类么）。</p>
<p>比如我们将一个样本集合里的index值也拿来作为一个特征去划分数据，那么这样的熵值肯定很高，用这样的特征去划分数据是没有意义的</p>
<p>不确定性越大，得到的熵值越大，当概率为0或者1的时候，logp就为0，就没有不确定性，熵值最小</p>
<h3 id="从一个天气情况与打球的实例来看决策树的过程"><a href="#从一个天气情况与打球的实例来看决策树的过程" class="headerlink" title="从一个天气情况与打球的实例来看决策树的过程"></a>从一个天气情况与打球的实例来看决策树的过程</h3><ol>
<li>数据如下</li>
</ol>
<div class="table-container">
<table>
<thead>
<tr>
<th>outlook</th>
<th>temperature</th>
<th>humidity</th>
<th>windy</th>
<th>play</th>
</tr>
</thead>
<tbody>
<tr>
<td>sunny</td>
<td>hot</td>
<td>high</td>
<td>FALSE</td>
<td>no</td>
</tr>
<tr>
<td>sunny</td>
<td>hot</td>
<td>high</td>
<td>TRUE</td>
<td>no</td>
</tr>
<tr>
<td>overcast</td>
<td>hot</td>
<td>high</td>
<td>FALSE</td>
<td>yes</td>
</tr>
<tr>
<td>rainy</td>
<td>mild</td>
<td>hight</td>
<td>FALSE</td>
<td>yes</td>
</tr>
<tr>
<td>rainy</td>
<td>cool</td>
<td>normal</td>
<td>FALSE</td>
<td>yes</td>
</tr>
<tr>
<td>rainy</td>
<td>cool</td>
<td>normal</td>
<td>TRUE</td>
<td>no</td>
</tr>
<tr>
<td>overcast</td>
<td>cool</td>
<td>normal</td>
<td>TRUE</td>
<td>yes</td>
</tr>
<tr>
<td>sunny</td>
<td>mild</td>
<td>hight</td>
<td>FALSE</td>
<td>no</td>
</tr>
<tr>
<td>sunny</td>
<td>cool</td>
<td>normal</td>
<td>FALSE</td>
<td>yes</td>
</tr>
<tr>
<td>rainy</td>
<td>mild</td>
<td>normal</td>
<td>FALSE</td>
<td>yes</td>
</tr>
<tr>
<td>sunny</td>
<td>mild</td>
<td>normal</td>
<td>TRUE</td>
<td>yes</td>
</tr>
<tr>
<td>overcast</td>
<td>mild</td>
<td>high</td>
<td>TRUE</td>
<td>yes</td>
</tr>
<tr>
<td>overcast</td>
<td>hot</td>
<td>normal</td>
<td>FALSE</td>
<td>yes</td>
</tr>
<tr>
<td>rainy</td>
<td>mild</td>
<td>high</td>
<td>TRUE</td>
<td>no</td>
</tr>
</tbody>
</table>
</div>
<ol>
<li>根节点用什么指标来划分呢</li>
</ol>
<p>第一步我们先算一下初始的熵值是多少</p>
<p>在历史数据中（14天）有9点打球、5天不打球，因此可以计算出熵值：</p>
<script type="math/tex; mode=display">
- \frac{9}{14} log_2{\frac{9}{14}} - \frac{5}{14} log_2{\frac{5}{14}} = 0.940</script><p>这里有如下的集中划分方式，我们依次计算一下划分后的熵值</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">1. 基于天气的划分</span><br><span class="line">    outlook:                        5/14 * 0.971 + 4/14 * 0 + 5/14 * 9.971 = 0.693</span><br><span class="line">        sunny（5天）</span><br><span class="line">            yes yes no no no        -1 * 2/5 * log2(2/5) - 3/5 * log2(3/5) = 0.971</span><br><span class="line">        overcast（4天）    </span><br><span class="line">            yes yes yes yes         -1 * 1 * log2(1) = 0</span><br><span class="line">        rainy（5天）</span><br><span class="line">            yes yes yes no no       -1 * 3/5 * log2(3/5) - 2/5 * log2(2/5) = 0.971</span><br><span class="line">2. 基于温度的划分</span><br><span class="line">    temperature:                    0</span><br><span class="line">        hot</span><br><span class="line">            yes yes no no </span><br><span class="line">        mild</span><br><span class="line">            yes yes yes yes no no</span><br><span class="line">        cool</span><br><span class="line">            yes yes yes no</span><br><span class="line">3. 基于湿度的划分</span><br><span class="line">    humidity</span><br><span class="line">        high</span><br><span class="line">            yes yes yes no no no no</span><br><span class="line">        normal</span><br><span class="line">            yes yes yes yes yes yes no</span><br><span class="line">4. 基于有风的划分</span><br><span class="line">    windy</span><br><span class="line">        false</span><br><span class="line">            yes yes yes yes yes yes no no</span><br><span class="line">        true</span><br><span class="line">            yes yes yes no no no</span><br></pre></td></tr></table></figure>
<h3 id="信息增益"><a href="#信息增益" class="headerlink" title="信息增益"></a>信息增益</h3><p>信息增益：表示特征X使得类Y的不确定性减少的程度（希望使用特征X分类后是同类的在一起）</p>
<p>从上面的例子我们可以得出，当我们基于天气进行划分时，信息增益为：0.940 - 0.693 = 0.247</p>
<p>同理可以得出其他分类的信息增益：gain(temperature)=0.029  gain(humidity)=0.152  gain(windy)=0.048</p>
<h3 id="关于计算熵值的算法"><a href="#关于计算熵值的算法" class="headerlink" title="关于计算熵值的算法"></a>关于计算熵值的算法</h3><p>考虑一下上面计算熵值的方法，我们根据每个特征计算了熵值，假设现在有一个特征是id值，依次增大的一个数，我们要以id作为特征，那么可以算出来熵值为0，增益是最大的，但是这个划分毫无意义</p>
<p>这种算法叫ID3算法，这个算法是有一定问题的，所以呢还是有很多其他评估熵值的算法</p>
<ol>
<li>ID3</li>
<li>C4.5：信息增益率（解决ID3问题，考虑自身熵）</li>
<li>使用GINI系数来做衡量标准</li>
</ol>
<p>GINI系数：$Gini(p) = \sum_{k=1}^K p_k(1-p_k) = 1 - \sum_{k=1}^K p_k^2$</p>
<h3 id="关于连续值特征的计算"><a href="#关于连续值特征的计算" class="headerlink" title="关于连续值特征的计算"></a>关于连续值特征的计算</h3><p>上面的例子都是一些离散值，而很多时候我们的数据都是连续值，那应该怎么处理呢？将连续值进行离散化</p>
<p>将连续数据进行排序，然后进行二分，可以得到离散数据，比如一堆数据从1到100的连续值，我们可以拿50当做分界点，就变成量两个离散值</p>
<h2 id="决策树剪枝策略"><a href="#决策树剪枝策略" class="headerlink" title="决策树剪枝策略"></a>决策树剪枝策略</h2><p>为什么要剪枝？决策树的过拟合风险非常大，理论上可以完全分得开数据，如果树足够庞大，每个叶子节点都是一个数据，但这样的树是没有意义的</p>
<h3 id="减枝策略"><a href="#减枝策略" class="headerlink" title="减枝策略"></a>减枝策略</h3><ol>
<li><p>预剪枝</p>
<p> 边建立决策树，边进行剪枝的操作（更实用）</p>
<p> 比如我们可以限制特征的数量（控制树的深度）、限制叶子节点个数、叶子节点样本数、信息增益量</p>
</li>
<li><p>后减枝</p>
<p> 建立完决策树后进行剪枝操作，通过一定的衡量标准</p>
</li>
</ol>
<script type="math/tex; mode=display">
C_{\alpha}(T)=C(T) + \alpha |T{leaf}|</script><p>叶子节点越多，损失越大</p>
<h2 id="实践"><a href="#实践" class="headerlink" title="实践"></a>实践</h2><p>我们使用两种方式去实践，一个使用sklearn库，一个直接使用python</p>
<h3 id="使用sklean实践决策树"><a href="#使用sklean实践决策树" class="headerlink" title="使用sklean实践决策树"></a>使用sklean实践决策树</h3><p>sklean 参数详解</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">1. criterion gini or entropy    指定评判标准</span><br><span class="line">2. splitter best or random 前者是在所有特征中找最好的切分点 后缀是在部分特征中（数据量大的时候）</span><br><span class="line">3. max_features None（所有），log2，sqrt，N特征小于50的时候一般使用所有的</span><br><span class="line">4. max_depth 数据少或者特征少的时候可以不管这个值，如果模型样本量多，特征也多的情况下，可以尝试限制一下</span><br><span class="line">5. min_samples_split 如果某节点的样本数少于min_samples_split，则不会继续再尝试选择最优特征来进行划分，如果样本量不大，不需要管这个值，如果样本量数量级非常大，则推荐增大这个值</span><br><span class="line">6. min_samples_leaf 这个值限制了叶子节点最少的样本数，如果某叶子节点数目小于样本数，则会和兄弟节点一起被剪枝，如果样本量不大，不需要管这个值，大些如10W可以尝试下5</span><br><span class="line">7. min_weight_fraction_leaf 这个值限制了叶子节点所有样本权重和的最小值，如果小于这个值，则会和兄弟节点一起被剪枝默认是0，就是不考虑权重问题。一般来说，如果我们有较多样本有缺失值，或者分类树样本的分布类别偏差很大，就会引入样本权重。这时我们就要注意这个值了。</span><br><span class="line">8. max_leaf_nodes 通过限制最大叶子节点数，可以防止过拟合，默认是&quot;None&quot;，即不限制最大的叶子节点数。如果加了限制，算法会建立在最大叶子节点数内最优的决策树。如果特征不多，可以考虑这个值，但是如果特征分成多的话，可以加以限制具体的值可以通过检查验证得到</span><br><span class="line">9. class_weight 指定样本各类别的权重，主要为了防止训练集某些类别的样本过多导致训练的决策树过于偏向这些类别，这里可以自己指定各个样本的权重如果使用&quot;balanced&quot;，则算法会自己计算权重，样本量少的类别所对应的样本权重会高</span><br><span class="line">10. min_impurity_split 这个值限制了决策树的增长，如果某节点的不纯度（基尼系数、信息增益、均方差，绝对差）小于这个阈值则该节点不再生成子节点。即为叶子节点</span><br><span class="line">11. n_estimators 要建立数的个数</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># brew install graphviz</span></span><br><span class="line">%matplotlib inline</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">from</span> sklearn.datasets.california_housing <span class="keyword">import</span> fetch_california_housing</span><br><span class="line">housing = fetch_california_housing()    <span class="comment"># 使用sklean内置房屋数据集</span></span><br><span class="line">housing.data.shape  <span class="comment"># 数据部分在data里，可以看下数据的大小规格</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> tree</span><br><span class="line">dtr = tree.DecisionTreeRegressor(max_depth=<span class="number">2</span>)</span><br><span class="line"><span class="comment"># 分别传入x与y的数据</span></span><br><span class="line">dtr.fit(housing.data[:, [<span class="number">6</span>,<span class="number">7</span>]], housing.target)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 构造可视化数据</span></span><br><span class="line">dot_data = tree.export_graphviz(</span><br><span class="line">    dtr,</span><br><span class="line">    out_file = <span class="keyword">None</span>,</span><br><span class="line">    feature_names = housing.feature_names[<span class="number">6</span>:<span class="number">8</span>],</span><br><span class="line">    filled = <span class="keyword">True</span>,</span><br><span class="line">    impurity = <span class="keyword">False</span>,</span><br><span class="line">    rounded = <span class="keyword">True</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 构造图形</span></span><br><span class="line"><span class="comment"># php install pydotplus</span></span><br><span class="line"><span class="keyword">import</span> pydotplus</span><br><span class="line">graph = pydotplus.graph_from_dot_data(dot_data)</span><br><span class="line">graph.get_nodes()[<span class="number">7</span>].set_fillcolor(<span class="string">"#FFF2DD"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 展示</span></span><br><span class="line"><span class="keyword">from</span> IPython.display <span class="keyword">import</span> Image</span><br><span class="line">Image(graph.create_png())</span><br><span class="line"></span><br><span class="line"><span class="comment"># 保存</span></span><br><span class="line">graph.write_png(<span class="string">"dtr_white_background.png"</span>)</span><br></pre></td></tr></table></figure>
<p>使用sklearn评估这些参数选择的效果<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn.model_selection <span class="keyword">import</span> train_test_split</span><br><span class="line">data_train, data_test, target_train, target_test = train_test_split(housing.data, housing.target, test_size=<span class="number">0.1</span>, random_state=<span class="number">0</span>)</span><br><span class="line">dtr = tree.DecisionTreeRegressor(random_state=<span class="number">0</span>)</span><br><span class="line">dtr.fit(data_train, target_train)</span><br><span class="line">dtr.score(data_test, target_test)</span><br></pre></td></tr></table></figure></p>
<p>决策树模型中有非常多的参数，我们往往需要尝试各种不同的参数，然后看看效果如何，就是拿各种参数组合来泡一下；非常庆幸的是sklean帮我们想到了这一点，它提供了grid_search工具帮我们做这一点<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn.grid_search <span class="keyword">import</span> GridSearchCV</span><br><span class="line"><span class="keyword">from</span> sklearn.ensemble <span class="keyword">import</span> RandomForestRegressor</span><br><span class="line">tree_param_grid = &#123;<span class="string">'min_samples_split'</span>:list((<span class="number">3</span>,<span class="number">6</span>,<span class="number">9</span>)), <span class="string">'n_estimators'</span>:list((<span class="number">10</span>,<span class="number">50</span>,<span class="number">100</span>))&#125;</span><br><span class="line"><span class="comment"># 第一个参数指定算法实例，第二个参数指定参数字典，第三个参数表示训练集的拆分个数，用于交叉验证</span></span><br><span class="line">grid = GridSearchCV(RandomForestRegressor(),param_grid=tree_param_grid, cv=<span class="number">5</span>)</span><br><span class="line">grid.fit(data_train, target_train)</span><br><span class="line">grid.grid_scores_, grid.best_params_, grid.best_score_</span><br></pre></td></tr></table></figure></p>
<h3 id="自实现一个决策树算法"><a href="#自实现一个决策树算法" class="headerlink" title="自实现一个决策树算法"></a>自实现一个决策树算法</h3><p>sklearn帮我们做了很多工作，使用起来也是非常方便，但是这一小节我们还是自己实现一个决策树算法，以便更深入的了解</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># @todo</span></span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/决策树/" rel="tag"># 决策树</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/10/18/1.html" rel="next" title="机器学习之其他细节">
                <i class="fa fa-chevron-left"></i> 机器学习之其他细节
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/11/04/1.html" rel="prev" title="机器学习之集成算法">
                机器学习之集成算法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="jackstraw" />
            
              <p class="site-author-name" itemprop="name">jackstraw</p>
              <p class="site-description motion-element" itemprop="description">人生的意义，不在于最终获得了什么，而在于曾经努力追求过什么</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#决策树"><span class="nav-number">1.</span> <span class="nav-text">决策树</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#决策树训练与测试"><span class="nav-number">1.1.</span> <span class="nav-text">决策树训练与测试</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#衡量标准-熵"><span class="nav-number">1.1.1.</span> <span class="nav-text">衡量标准-熵</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#从一个天气情况与打球的实例来看决策树的过程"><span class="nav-number">1.1.2.</span> <span class="nav-text">从一个天气情况与打球的实例来看决策树的过程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#信息增益"><span class="nav-number">1.1.3.</span> <span class="nav-text">信息增益</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#关于计算熵值的算法"><span class="nav-number">1.1.4.</span> <span class="nav-text">关于计算熵值的算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#关于连续值特征的计算"><span class="nav-number">1.1.5.</span> <span class="nav-text">关于连续值特征的计算</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#决策树剪枝策略"><span class="nav-number">1.2.</span> <span class="nav-text">决策树剪枝策略</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#减枝策略"><span class="nav-number">1.2.1.</span> <span class="nav-text">减枝策略</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实践"><span class="nav-number">1.3.</span> <span class="nav-text">实践</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#使用sklean实践决策树"><span class="nav-number">1.3.1.</span> <span class="nav-text">使用sklean实践决策树</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#自实现一个决策树算法"><span class="nav-number">1.3.2.</span> <span class="nav-text">自实现一个决策树算法</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">jackstraw</span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: false,
        appId: 'lQM75w94ggNR0TjX61NLerrg-gzGzoHsz',
        appKey: 'I2wtQ2rd9KtoJmcEOiYG9zqT',
        placeholder: '如需帮助，请留下邮箱',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
    var infoEle = document.querySelector('#comments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0){
      infoEle.childNodes.forEach(function(item) {
        item.parentNode.removeChild(item);
      });
    }
  </script>



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("lQM75w94ggNR0TjX61NLerrg-gzGzoHsz", "I2wtQ2rd9KtoJmcEOiYG9zqT");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
